package com.condroid;

import java.io.IOException;
import java.io.OutputStream;

/**
 * This class is used for command issue.
 * Every class need to issue command need
 * to use the instant of this class.
 * @author JUN GAO
 * Condroid Summer CSD 2011 - KTH
 */
public class CmdCmit {
	private OutputStream outStream;
	private CmdParser parser;
	private String[] cmd;
	private int type;
	
	public CmdCmit(){
		parser = new CmdParser();
	}
	
	/**
	 * @param The OutStream used for issue
	 * command
	 */
	public CmdCmit(OutputStream outStream){
		this.outStream = outStream;
		parser = new CmdParser();
	}
	
	/**
	 * @param outStream The OutStream used for issue
	 * command
	 */
	public void setOutStream(OutputStream outStream){
		this.outStream = outStream;
	}

	/**
	 * @param cmdOriginal The command provided by user.
	 * @return if command is correct, method will return
	 * true or will return false.
	 */
	public boolean setCmd(String cmdOriginal) {
		// TODO parsing and get the real command or action
		parser.setCmd(cmdOriginal);
		if (parser.checkCmd()) {
			cmd = parser.parseCmd();
			type = parser.cmdType();
			return true;
		} else
			return false;
	}
	
	/**
	 * After provide the command use {@link #setCmd(String)} use this 
	 * method to execute it.
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public void exeCmd() throws IOException, InterruptedException{
		//TODO issue command to device or execute action for ConDroid
		int i;
		switch(type){
		case ConstantData.OUTERCMD:
			cmd[0]+= ConstantData.NEWLINE;
			outStream.write(cmd[0].getBytes());
			break;
		case ConstantData.SHTCUTCMD:
			for(i=0;i<cmd.length;i++){
				cmd[i]+= ConstantData.NEWLINE;
				outStream.write(cmd[i].getBytes());
				Thread.sleep(SHTCUTISSUEWAITTIME);
			}
			break;
		case ConstantData.INNEREXECMD:
			innerCmdExecute();
			break;
		default:
			break;
		}
	}
	
	private void innerCmdExecute(){
		//TODO inner command execution
	}
	
	private final int SHTCUTISSUEWAITTIME = 500;
}
